package kit.edu.lego.gruppe3.bluetooth;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import lejos.nxt.LCD;
import lejos.nxt.comm.BTConnection;
import lejos.nxt.comm.Bluetooth;
import lejos.nxt.comm.NXTConnection;

public class BluetoothClient {

	// **********************
	// REQUEST code constants
	// **********************

	// request for the detour gate to open
	public static final int GATE_OPEN = 3;

	// *********************
	// RETURN code constants
	// *********************

	public static int REQUEST_DENIED = -1;
	public static int REQUEST_ACCEPTED = 1;

	// Cannot constantly send requests, but only once every random 3 seconds
	private static long last_request_time = 0;

	/**
	 * Sends a bluetooth request to central NXT
	 * @param requestCode
	 * @return
	 */
	public static int sendRequest(int requestCode) {
		if (System.currentTimeMillis() - last_request_time < 3.0) {
			return REQUEST_DENIED;
		}
		last_request_time = System.currentTimeMillis();

		int ret = -1;
		DataInputStream input = null;
		DataOutputStream output = null;

		try {
			LCD.clear();
			LCD.drawString("Connecting to central NXT", 0, 0);

			// Open bluetooth connection
			BTConnection btConn = Bluetooth.connect("00165306b259",
					NXTConnection.LCP);

			try {
				if (btConn == null) {
					LCD.clear();
					LCD.drawString("Connection error", 0, 0);
					return REQUEST_DENIED;
				}

				LCD.clear();
				LCD.drawString(Bluetooth.getLocalAddress(), 0, 0);
				LCD.drawString("Connected to central NXT", 0, 1);
				LCD.drawString("Signal: " + btConn.getSignalStrength(), 0, 3);

				// Open output data stream
				// Data written to that stream will be sent to remote device
				output = btConn.openDataOutputStream();
				// Open input data stream
				// Stream contains data that has been sent to local device
				input = btConn.openDataInputStream();

				if (output == null || input == null) {
					LCD.clear();
					LCD.drawString("I/O failed", 0, 0);
					btConn.close();
					return REQUEST_DENIED;
				}

				// Write data to the stream
				try {
					output.writeInt(requestCode);
					output.flush();
				} catch (IOException e) {
					LCD.drawString("Requesting failed", 0, 4);
					return REQUEST_DENIED;
				}
				LCD.drawString("Request sent...", 0, 4);

				// Read response data from stream
				try {
					while (input.available() < 1) {

					}
					ret = input.readInt();
					LCD.drawString("Response: " + ret, 0, 5);
				} catch (IOException e) {
					LCD.drawString(e.toString(), 0, 4);
					return REQUEST_DENIED;
				}
				return ret;
			} finally {
				if (btConn != null) {
					btConn.close();
				}
			}
		} catch (Exception e) {
			return REQUEST_DENIED;
		}
	}
}
